package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.iot.base.bean.Device;
import com.iot.base.service.req.RemoveDeviceParam;
import com.iot.common.utils.LogUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.adapter.MainBottomTabFragmentAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.fragment.DeviceFragment;
import com.yx.cloud.fragment.MessageFragment;
import com.yx.cloud.fragment.UserInfoFragment;
import com.yx.cloud.utils.AtyContainer;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.StatusBarColorUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.NoSlidingViewPager;

import java.util.ArrayList;
import java.util.List;

public class MainBottomTabActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    public NoSlidingViewPager vp;
    public RadioGroup rg;
    public LinearLayout mBottomTabRlDelete;
    private List<Fragment> list = new ArrayList<Fragment>();
    private RadioButton mRbDevice, mRbMessage, mRbUser;
    private MainBottomTabFragmentAdapter adapter;
    private boolean isSelectedDeleteDevice = false;
    private long mExitTime = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("tab  onCreate : ");
        setContentView(R.layout.activity_bottom_tab_activity);
        initView();//初始化控件
        initPage();//初始化页面
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int recreate = AppContext.get().isRecreate();
        LogUtils.i("tab  onNewIntent : " + recreate);
        if (recreate == 1) {
            recreate();//语言切换刷下界面
        } else if (recreate == 2) {
            //这里是 配网成功后跳转到这边需要再更新一下设备列表,不然设备名称不会改变
            AppContext.getAccountService().getDeviceList();

//            int currentItem = vp.getCurrentItem();
//            vp.setCurrentItem(currentItem);//设置默认选择界面
//            LogUtils.i("tab  onNewIntent currentItem : " + currentItem);
//            if (currentItem == 1) {
//                AppContext.getAccountService().getDeviceList();
//            }
        }
        AppContext.get().setRecreate(0);//恢复默认
    }

    //控件初始化控件
    private void initView() {
        vp = findViewById(R.id.pager);
        mRbMessage = findViewById(R.id.bottom_tab_rb_message);
        mRbDevice = findViewById(R.id.bottom_tab_rb_device);
        mRbUser = findViewById(R.id.bottom_tab_rb_user);
        rg = findViewById(R.id.bottom_tab_rg);
        mBottomTabRlDelete = findViewById(R.id.bottom_tab_rl_delete);

        vp.addOnPageChangeListener(this);//设置页面切换时的监听器
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.bottom_tab_rb_message) {
                    vp.setCurrentItem(0);//设置默认选择界面
                } else if (checkedId == R.id.bottom_tab_rb_device) {
                    vp.setCurrentItem(1);//设置默认选择界面
                } else if (checkedId == R.id.bottom_tab_rb_user) {
                    vp.setCurrentItem(2);//设置默认选择界面
                }
            }
        });
    }

    /*初始化Fragment*/
    private void initPage() {
        StatusBarColorUtils.setStatusBarFontColor(this, R.color.background_color, "0");//设置黑色
        MessageFragment message_fragment = new MessageFragment();
        DeviceFragment device_fragment = new DeviceFragment();
        UserInfoFragment user_fragment = new UserInfoFragment();

        list.add(message_fragment);
        list.add(device_fragment);
        list.add(user_fragment);

        //绑定Fragment适配器
        adapter = new MainBottomTabFragmentAdapter(getSupportFragmentManager(), list);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(3);
        vp.setNoScroll(true);
        mRbDevice.setChecked(true);//设置默认选择底部
        mBottomTabRlDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeviceFragment deviceFragment = (DeviceFragment) adapter.getItem(1);

                if (deviceFragment.selectList.size() != 0) {
                    List<Device> removeDeviceList = new ArrayList<>();
                    for (int i = 0; i < deviceFragment.selectList.size(); i++) {
                        if (deviceFragment.selectList.get(i)) {
                            removeDeviceList.add(deviceFragment.newDeviceList.get(i));
                        }
                    }
                    if (removeDeviceList.size() == 0) {
                        ToastUtil.showShort(MainBottomTabActivity.this, R.string.U_T_Delete_NoSelect);
                    } else {
                        deleteDeviceHintDialog(getString(R.string.U_Delete), getString(R.string.H_Delete_Tip).replace("{X}", deviceFragment.count + ""), removeDeviceList);
                    }
                }
            }
        });
    }


    @Override
    public void onPageScrollStateChanged(int position) {

    }//arg0 ==1的时候表示正在滑动，arg0==2的时候表示滑动完毕了，arg0==0的时候表示什么都没做，就是停在那。

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }//表示在前一个页面滑动到后一个页面的时候，在前一个页面滑动前调用的方法

    @Override
    public void onPageSelected(int arg0) {//arg0是表示你当前选中的页面位置Postion，这事件是在你页面跳转完毕的时候调用的。
        LogUtils.i("tab  onPageSelected : " + arg0);
        if (arg0 == 0) {
            mRbMessage.setChecked(true);
            ((MessageFragment) list.get(0)).getDeviceMessage();
        } else if (arg0 == 1) {
            mRbDevice.setChecked(true);
        } else if (arg0 == 2) {
            mRbUser.setChecked(true);
        }
    }

    public void deviceOffLineHintDialog() {
        Dialog dialog = new Dialog(MainBottomTabActivity.this);
        dialog.setContentView(R.layout.device_offline_hint_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.tv_I_knowConfirm);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void deleteDeviceHintDialog(String dialogTitle, String content, List<Device> removeDeviceList) {
        Dialog dialog = new Dialog(MainBottomTabActivity.this);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_content);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setVisibility(View.VISIBLE);
        mTvDialogContent.setText(content);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                RemoveDeviceParam param = new RemoveDeviceParam();
                param.setDeviceList(removeDeviceList);
                AppContext.getAccountService().removeDevice(param);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //禁止划屏关闭界面
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            int navigationMode = DisplayUtil.getNavigationMode(this);
            if (navigationMode == 0) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, getString(R.string.U_T_Exit), Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    AtyContainer.getInstance().finishAllActivity();
                }
                return true;
            } else if (navigationMode == 2) {
                //全屏
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}